#include "dataiomanager.h"

#include <QDir>
#include <QPluginLoader>
#include <QCoreApplication>
#include <QDebug>

#include <QMessageBox>

struct DataIOManagerPrivate {
    QList<DataIOInterface*> modules;
};



DataIOManager& DataIOManager::instance()
{
    static DataIOManager instance;
    return instance;
}

DataIOInterface *DataIOManager::ioModuleByName(const QString &moduleName)
{
    for (const auto& module : m_d->modules) {
        if (!module) continue;
        if (module->name() == moduleName) return module;

    }
    qDebug() << "data io no module:" << moduleName;
    return nullptr;
}

QList<DataIOInterface *> DataIOManager::modules() const
{
    return m_d->modules;
}

void DataIOManager::loadDataIos()
{
    QDir pluginsDir(QCoreApplication::applicationDirPath());

#if defined(Q_OS_WIN)
    if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
        pluginsDir.cdUp();
#endif

    pluginsDir.cd("ios");
    QStringList nameFilters;
    nameFilters << "*.dll";  // 仅加载.dll文件
    foreach (QString fileName, pluginsDir.entryList(nameFilters, QDir::Files)) {
        QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));

        QObject *plugin = pluginLoader.instance();
        if (plugin) {
            DataIOInterface* module = qobject_cast<DataIOInterface*>(plugin);
            if (module) {
                m_d->modules.append(module);
                module->initialize();
                qDebug() << "Loaded plugin:" << module->name();
            }
        } else {
            qDebug() << "Failed to load plugin:" << fileName << pluginLoader.errorString();
        }
    }
}

DataIOManager::DataIOManager() {
    m_d = new DataIOManagerPrivate;
}

DataIOManager::~DataIOManager()
{
    delete m_d;
}
